package com.controller.server;

import com.rmi.RMIInterface;
import com.rmi.RMIInterfaceImpl;
import com.rmi.RMITLSClientSocketFactory;
import com.rmi.RMITLSServerSocketFactory;
import com.util.Constant;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import java.rmi.AlreadyBoundException;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

/**
 * Created by Phillip on 2014/4/15.
 */
public class RMIServer {

    public static void main(String[] args) {

        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }

        Logger logger = Logger.getLogger(RMIServer.class);
        PropertyConfigurator.configure(Constant.RMISER_PRO_STRING);
        logger.info("RMI server starts...");

        RMIInterfaceImpl rmiInterface = new RMIInterfaceImpl();

        try {
            RMIInterface stub = (RMIInterface) UnicastRemoteObject.exportObject(rmiInterface, 0,
                    new RMITLSClientSocketFactory(Constant.SER_KEYSTORE_STRING, Constant.CLI_KEYSTORE_STRING, "huyifei"),
                    new RMITLSServerSocketFactory(Constant.SER_KEYSTORE_STRING, Constant.CLI_KEYSTORE_STRING, "huyifei"));
            logger.debug("UnicastRemoteObject.exportObject done");

            Registry registry = LocateRegistry.createRegistry(1099,
                    new RMITLSClientSocketFactory(Constant.SER_KEYSTORE_STRING, Constant.CLI_KEYSTORE_STRING, "huyifei"),
                    new RMITLSServerSocketFactory(Constant.SER_KEYSTORE_STRING, Constant.CLI_KEYSTORE_STRING, "huyifei"));
            logger.debug("LocateRegistry.createRegistry done\r\nstart binding...");
//            Registry registry = LocateRegistry.getRegistry();
            registry.bind(Constant.RMISERVER_STRING, stub);
            logger.debug("binding done");

        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (AlreadyBoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
